package com.example.demo.security.config;

import com.example.demo.security.errorthrow.RestAuthorizationEntryPoint;
import com.example.demo.security.errorthrow.RestfulAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.Filter;

@Configuration
//开启接口权限判断
@EnableGlobalMethodSecurity(prePostEnabled=true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
//                .loginProcessingUrl("/login")
                //登录后跳转的地址 Post请求
                .successForwardUrl("/admin/index");

        http.authorizeRequests()
                .antMatchers("/**/**.html").permitAll()
                .antMatchers("/**.html").permitAll()

                //所有请求必须验证
                .anyRequest().authenticated();

        //关闭csrf
        http.csrf().disable();
        http.exceptionHandling()
                //权限不足错误抛出
                .accessDeniedHandler(restfulAccessDeniedHandler);
                //未登录错误抛出
            //  .authenticationEntryPoint(restAuthorizationEntryPoint);

    }
}
